package com.xhu.handler;

import com.xhu.exceptions.CompeteException;
import com.xhu.exceptions.UserLoginException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class ProfilePhotoHandler {

    private static final String PATH = "D:\\crmsystem\\profile photo";

    public String uplordFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new CompeteException("文件为空");
        }
        File uploadrDir = new File(PATH);
        if (!uploadrDir.exists()) {
            boolean mkdir = uploadrDir.mkdir();

            if (!mkdir) {
                throw new UserLoginException("创建目录失败");
            }

        }

        String originFileName = file.getOriginalFilename();
        //判空
        if (!StringUtils.hasText(originFileName)) {
            throw new CompeteException("文件名字为空");
        }
        //获取后缀
        String suffixName = originFileName.substring(originFileName.lastIndexOf("."));
        //随机生成名字
        String fileanme = UUID.randomUUID() + suffixName;
        File localFile = new File(PATH, fileanme);
        //移动文件到本地目录
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CompeteException("上传失败");
        }

        return localFile.getPath();

    }
}
